package com.ian.controller;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.nio.file.*;
import java.util.Iterator;
import java.util.List;

/**
 * @author Witt
 * @version 1.0.0
 * @date 2022/5/7
 */
@Controller
public class TestController {
    private static int counter;

    @PostMapping("/test")
    @ResponseBody
    public String test(@RequestParam("name") String name) {
        return name + (counter++);
    }

    @GetMapping("/toUploadPage")
    public String toUploadPage() {
        return "uploadPage";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam String name, @RequestPart MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        System.out.format("upload name: %s; original file name: %s%n", uploadFile.getName(), uploadFile.getOriginalFilename());
        /*
        注意：有个报错：org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field uploadFile exceeds its maximum permitted size of 1048576 bytes.
        RCA: 意思是上传的文件大小超过了 1M。
        SOLUTION: 目前暂时不上传超过 1M 的文件，以后有空研究下如何去掉该限制。
         */
        Path path = Paths.get(String.format("data%s%s", FileSystems.getDefault().getSeparator(), uploadFile.getOriginalFilename()));
        Files.write(path, uploadFile.getBytes());
        return name + ": upload success!";
    }
}
